package com.carrot.uaa.authorization.response;

import com.carrot.common.core.domain.R;
import com.carrot.uaa.constant.BusinessCodeConstants;
import org.springframework.core.ParameterizedTypeReference;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.MediaType;
import org.springframework.http.converter.GenericHttpMessageConverter;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.security.oauth2.core.OAuth2Error;
import org.springframework.security.oauth2.core.http.converter.OAuth2ErrorHttpMessageConverter;

import java.util.Map;
import java.util.Optional;

/**
 * 重写认证失败响应格式
 */
public class MyOAuth2ErrorHttpMessageConverter extends OAuth2ErrorHttpMessageConverter {

    private final GenericHttpMessageConverter<Object> jsonMessageConverter = HttpMessageConverters.getJsonMessageConverter();
    private static final ParameterizedTypeReference<Map<String, Object>> STRING_OBJECT_MAP = new ParameterizedTypeReference<Map<String, Object>>() {
    };
    @Override
    protected void writeInternal(OAuth2Error oauth2Error, HttpOutputMessage outputMessage) throws HttpMessageNotWritableException {
        try {
            //Map<String, String> errorParameters = this.errorParametersConverter.convert(oauth2Error);
            String error = Optional.ofNullable(oauth2Error.getDescription()).orElse(oauth2Error.getErrorCode());
            R resultWrapper = R.fail(BusinessCodeConstants.AUTH_ERROR,error);
            this.jsonMessageConverter.write(resultWrapper, STRING_OBJECT_MAP.getType(), MediaType.APPLICATION_JSON,
                    outputMessage);
        }
        catch (Exception ex) {
            throw new HttpMessageNotWritableException(
                    "An error occurred writing the OAuth 2.0 Error: " + ex.getMessage(), ex);
        }
    }
}
